package org.restql.db.operation;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.restql.db.Utility;
import org.restql.db.resource.DatabaseResource;
import org.restql.db.resource.ModifiableDatabaseResource;
import org.restql.db.resource.RequestResource;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DatabaseUpdate extends DatabasePutPost {

	private static Log logger = LogFactory.getLog(DatabaseUpdate.class);

	public DatabaseUpdate(DatabaseResource databaseResource, RequestResource requestResource) {
		super(databaseResource, requestResource);
	}


	// Node containing children of fields to update
	protected void doOperation(Map<String, String> fieldValueMap) throws SQLException {
		List<String> fieldList = new ArrayList<String>(); 
		for (String key : fieldValueMap.keySet()) {
			fieldList.add(Utility.nameJs2Sql(key) + " = '" + fieldValueMap.get(key) + "'");
		}

		String constructedSQL = this.databaseResource.getUpdateString(this.requestResource, fieldList);

		PreparedStatement stmt =
			getConnection().prepareStatement(constructedSQL);

		logger.info("Executing: " + constructedSQL);
		stmt.executeUpdate();
	}

}
